package service.impl.security;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import service.impl.BaseDataServiceImpl;
import service.interf.security.IResource;

import common.impl.exception.ServiceException;

import dao.interf.IAuthorityDAO;
import dao.interf.IResourceAuthorityDAO;
import dao.interf.IResourceDAO;
import dao.interf.IResourceTypeDAO;
import dao.pojo.Authority;
import dao.pojo.Resource;
import dao.pojo.ResourceAuthority;
import dao.pojo.ResourceType;


/**
 *  Title:ResourceImpl 
 *  Description:提供资源相关接口
 *  @author yangl
 *  @date 2012-11-30
 *  @version 1.0
 */
public class ResourceImpl extends BaseDataServiceImpl  implements IResource{
	
	/**安全资源DAO接口*/
	private IResourceDAO resDao;
	/**安全资源类型DAO接口*/
	private IResourceTypeDAO rtypeDao;
	/**安全资源授权DAO接口*/
	private IResourceAuthorityDAO rauthDao;
	/**安全权限DAO接口*/
	private IAuthorityDAO authDao;
	
	/**
	 * Title:setAuthDao
	 * Description:为Spring框架注入IResourceDAO提供方法
	 * @param resDao 传入ResourceDAO
	 */
	public void setResDao(IResourceDAO resDao) {
		this.resDao = resDao;
	}
	
	/**
	 * Title:setAuthDao
	 * Description:为Spring框架注入IResourceTypeDAO提供方法
	 * @param rtypeDao 传入ResourceTypeDAO
	 */
	public void setRtypeDao(IResourceTypeDAO rtypeDao) {
		this.rtypeDao = rtypeDao;
	}
	
	/**
	 * Title:setAuthDao
	 * Description:为Spring框架注入IResourceAuthorityDAO提供方法
	 * @param rauthDao 传入ResourceAuthorityDAO
	 */
	public void setRauthDao(IResourceAuthorityDAO rauthDao) {
		this.rauthDao = rauthDao;
	}
	
	/**
	 * Title:setAuthDao
	 * Description:为Spring框架注入IAuthorityDAO提供方法
	 * @param authDao 传入AuthorityDAO
	 */
	public void setAuthDao(IAuthorityDAO authDao) {
		this.authDao = authDao;
	}
	/******************resource ************************/
	/**
	 * Title:addResource 
	 * Description:添加资源
	 * @param model:模型
	 * @return 成功：新增资源编号 , 失败 错误编号
	 */
	public String addResource(Resource model)  throws Exception{
		Resource r = new Resource();
		r.setUrl(model.getUrl());
		r.setTitle(model.getTitle());
		if(null != model.getResourceType()){
			if (null != model.getResourceType().getResourceTypeId()){
				ResourceType rt = (ResourceType)rtypeDao.findById(model.getResourceType().getResourceTypeId());
				if(null != rt) {
					r.setResourceType(rt);
				}
			}
		}
		
		r = (Resource)resDao.save(r);
		return r.getResourceType().getResourceTypeId().toString();
	}
	
	/**
	 * Title:delResource
	 * Description: 删除资源
	 * @param model:模型
	 * @return 成功：1 , 失败 错误编号
	 */
	public String delResource(Resource model)  throws Exception{
		String[] idS = model.getIds().split(",");
		for(int i=0; i<idS.length; i++){
			resDao.deleteById(Integer.parseInt(idS[i]));
		}
		return "1";
	}
	
	/**
	 * Title:editResource
	 * Description: 编辑资源
	 * @param model:模型
	 * @return 成功：1 , 失败 错误编号
	 */
	public String editResource(Resource model) throws Exception{
		Resource r = null;
		r = (Resource) resDao.findById(model.getResourceId());
		if(null == r)
			throw new ServiceException("ERR-0091");
		r.setResourceId(model.getResourceId());
		r.setUrl(model.getUrl());
		r.setTitle(model.getTitle());
		
		resDao.update(r);
		return "1";
	}
	
	/**
	 * Title:getResourceAuthorities
	 * Description:获取资源权限
	 * @param ResourceId:资源编号
	 * @return 成功：资源权限数组，失败：错误编号
	 */
	public String getResourceAuthorities(Integer ResourceId) throws Exception{
		Resource r  = null;
		try{
			r = (Resource) resDao.findById(ResourceId);
		}catch(Exception e){}
		if(null == r)
			throw new ServiceException("ERR-0091");
		Set lst = r.getResourceAuthorities();
		JSONArray jarr = new JSONArray();
		if(null != lst){
			for(Iterator<ResourceAuthority> ite = lst.iterator();ite.hasNext();){
				ResourceAuthority ra = ite.next();
				JSONObject jobj = new JSONObject();
				jobj.put("authority", ra.getAuthority().getAuthority());
				jarr.add(jobj);
			}
		}
		JSONObject jret = new JSONObject();
		jret.put("rows", jarr);
		return jret.toString();
	}
	/**
	 * Title:addResourceAuthFromFile
	 * Description:从文本提取资源-权限，前提为已通过该文本将权限存储
	 * @return "1"
	 */
	public String addResourceAuthFromFile() throws Exception{
		FileInputStream fis = new FileInputStream("E://Resource_authority.txt"); 
		BufferedReader br = new BufferedReader(new InputStreamReader(fis));
		String line=null;
		while((line=br.readLine())!=null){
			//:前为资源，后为权限组
			String[] ab = line.split(":");
			if(ab.length!=2)
				throw new ServiceException("文本中表达示不正确！");
			String res = ab[0].trim();
			String auths = ab[1].trim();
			List<Resource> rlst = resDao.findByProperties(new String[]{"url"}, new Object[]{res});
			Resource r = rlst.get(0);
			//多个权限以&分开
			String[] auth = auths.split("&");
			for(int i=0;i<auth.length;i++){
				List<Authority> alst = authDao.findByProperties(new String[]{"authority"}, new Object[]{auth[i]});
				Authority a = alst.get(0);
				ResourceAuthority ra = new ResourceAuthority();
				ra.setResource(r);
				ra.setAuthority(a);
				rauthDao.save(ra);
			}
		}
		return "1";
	}
	
	/**
	 * Title:updateResourceAuthority
	 * Description: 更新资源权限
	 * @param ResourceAuthorities:资源权限
	 */
	public String updateResourceAuthority(Integer resourceId,String authorities) throws Exception{
		Resource r = null;
		r = (Resource)resDao.findById(resourceId);
		if(null == r)
			throw new ServiceException("ERR-0091");
		Map<String,Object>map = new HashMap<String,Object>();
		map.put("Resource", r);
		ArrayList<String> arr = new ArrayList<String>();
		//清除authority
		rauthDao.deleteByProperties(new String[]{"resource.resourceId"}, new Object[]{resourceId},null);
		if(StringUtils.isEmpty(authorities)){
			return "1";
		}
		//串以逗号隔开,第一个为ResourceId，后面依次为多个权限
		String[] auths = authorities.split(",");
		int len=auths.length;
		for(int i=0;i<len;i++){
			Authority a = null;
			a = (Authority)authDao.findById(auths[i]);
			if(a != null){
				ResourceAuthority ra = new ResourceAuthority();
				ra.setAuthority(a);
				ra.setResource(r);
				rauthDao.save(ra);
				//资源权限保存
				arr.add(a.getAuthority());
			}
		}
		//修改资源内存权限
//		security.MyInvocationSecurityMetadataSource.changeAuthority(r.getUrl(), arr);
		return "1";
	}
	
	
	/**
	 * Title:updateResourceAuthority
	 * Description: 更新权限资源
	 * @param ResourceAuthorities:资源权限
	 */
	public String updateAuthorityResource(String authority,String ids) throws Exception{
		//串以逗号隔开,第一个为ResourceId，后面依次为多个权限
		Authority r = null;
		r = (Authority)authDao.findById(authority);
		if(null == r)
			throw new ServiceException("ERR-0091");//需要改
		Map<String,Object>map = new HashMap<String,Object>();
		map.put("Authority", r);
		ArrayList<String> arr = new ArrayList<String>();
		//清除resource
		rauthDao.deleteByProperties(new String[]{"authority.authority"}, new Object[]{r.getAuthority()},null);
		if(StringUtils.isEmpty(ids)){
			return "1";
		}
		String[] res = ids.split(",");
		int len=res.length;
		
		for(int i=0;i<len;i++){
			Resource a = null;
			a = (Resource)resDao.findById(Integer.parseInt(res[i]));
			if(a != null){
				ResourceAuthority ra = new ResourceAuthority();
				ra.setResource(a);
				ra.setAuthority(r);
				rauthDao.save(ra);
				//资源权限保存
				arr.add(r.getAuthority());
			}
		}
		//修改资源内存权限
//		security.MyInvocationSecurityMetadataSource.changeAuthority(r.getUrl(), arr);
		return "1";
	}
	
	
	/**
	 * Title:getAllResourcesWithAuth
	 * Description:获取所有资源和权限
	 * @return map
	 * @throws Exception
	 */
	public Map getAllResourcesWithAuth() throws Exception{
		Map<String,ArrayList> map = new HashMap<String,ArrayList>();
		List lst = null;
		lst = rauthDao.findAll(null);
		if(null != lst){
			ArrayList arr = null;
			for (Iterator<ResourceAuthority> l = lst.iterator(); l.hasNext();) {
				ResourceAuthority ra = l.next();
				Resource r = ra.getResource();
				Authority a = ra.getAuthority();
				String url = r.getUrl();
				if(!map.containsKey(url)){
					arr = new ArrayList();
					map.put(url, arr);
				}
				arr = map.get(url);
				arr.add(a.getAuthority());
			}
		}
		return map;
	}
	
	
	
	/************************ Resource type **********************/
	
	
	
	private int count = 0;
	private static String home = "/qidong";
	private static String end = ".action";
	private static String dir = "E:\\Workspaces\\MyEclipse\\qidong\\WebRoot\\pages";
	/**
	 * Title:fetchDirAction
	 * Description: @遍历某目录下面的文件,(隐藏文件除外)  注:未过滤含+号等的记录
	 * @param path: 需要查找的顶级目录
	 * @param hs:把查找的目标存入set
	*/
	private void fetchDirAction(String path,HashSet<String> hs) throws IOException{
		File fp = new File(path);
		File[] files = fp.listFiles();
		if(null != files){
			for(File file : files){
				if(!file.isDirectory()&&!file.isHidden()){
					String fname = file.getName();
					int len = file.getName().length();
					if(!fname.substring(len-4, len).equals(".jsp")&&!fname.substring(len-3, len).equals(".js"))
						continue;//如果还是jsp或js则返回
					FileInputStream fis = new FileInputStream(file);
					InputStreamReader isr = new InputStreamReader(fis);
					BufferedReader br = new BufferedReader(isr);
					String line = null;
					while((line=br.readLine())!=null){
						int ind=-1;
						int ond=-1;
						String str = null;
						if((ind=line.indexOf(home))>-1 && (ond=line.indexOf(end))>-1){
							str = line.substring(ind, ond+end.length());
							hs.add(str);
							count++;
						}
					}
					br.close();
				}
				if(file.isDirectory()&&!file.isHidden()){
					fetchDirAction(file.getPath(),hs);
				}
			}
		}
	}
	/**
	 * Title:fetchDirJsp
	 * Description: @遍历jsp目录（隐藏文件除外）
	 * @param path: 需要查找的顶级目录
	 * @param hs:把查找的目标存入set
	*/
	private void fetchDirJsp(String path,HashSet<String> hs) throws IOException{
		File fp = new File(path);
		File[] files = fp.listFiles();
		if(null != files){
			for(File file : files){
				if(!file.isDirectory()&&!file.isHidden()){
					int len = file.getName().length();
					if(file.getName().substring(len-4, len).equals(".jsp")){
						String str = file.getPath().replace("\\", "/").replaceAll("/WebRoot", "");
						str = str.substring(str.indexOf(home));
						hs.add(str);//在这里根据情况截取jsp路径
						count++;
					}
				}
				if(file.isDirectory()&&!file.isHidden()){
					fetchDirJsp(file.getPath(),hs);
				}
			}
		}
	}
}
